<template>
  <el-card>
    <el-collapse-transition>
      <div v-show="show_1">
        <div>
          <el-input placeholder="请输入关键字(名字)" v-model="search" style="width: 15%; margin-right: 10px;">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-button type="primary" plain @click="setSearchicket" :loading="searchLoading">查询</el-button>
        </div>
        <el-table :data="tableData" style="width: auto; height: auto;  margin-top: 30px;" stripe border
          :header-cell-style="{ background: '#f0f9ff', textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
          <el-table-column label="序号" type="index" width="80">
          </el-table-column>
          <el-table-column label="日期" prop="date" width="150">
          </el-table-column>
          <el-table-column label="车次" prop="trainNumber" width="130">
          </el-table-column>
          <el-table-column label="起始站" prop="startStation" width="150">
          </el-table-column>
          <el-table-column label="终点站" prop="arriveStation" width="150">
          </el-table-column>
          <el-table-column label="价格" prop="price" width="120">
          </el-table-column>
          <el-table-column label="乘车人" prop="customerName" width="150">
          </el-table-column>
          <el-table-column label="座位类型" width="150">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.seatType === 0" >商务座</el-tag>
              <el-tag v-if="scope.row.seatType === 1" type="warning" >一等座</el-tag>
              <el-tag v-if="scope.row.seatType === 2" type="info" >二等座</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否支付" width="150">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">已支付</el-tag>
              <el-tag v-if="scope.row.status === 0" type="danger">未支付</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === 0" type="info" size="small" disabled
                style="width:98px">未支付</el-button>
              <div v-if="scope.row.status === 1">
                <el-button type="primary" size="small" @click="transFormShow(scope.row, false, true)">改签</el-button>
                <el-button type="danger" size="small" slot="reference"
                  @click=setDeleteTiceket(scope.row.id)>退票</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center; margin-top: 50px;">
          <el-pagination @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" :total=page.total
            :page-size=page.pageSize :current-page.sync=page.currentPage>
          </el-pagination>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="show_2">
        <div>
          <el-form :inline="true" :model="form" :rules="rulesForm" ref="form">
            <el-form-item prop="date" label="日期" style=" margin-left: 50px;">
              <el-date-picker type="date" placeholder="选择日期" style="width: 180px;" v-model="form.date"></el-date-picker>
            </el-form-item>
            <el-form-item label="出发车站" style=" margin-left: 88px;" prop="start">
              <el-input placeholder="请输入车站" style="width: 180px;" v-model="form.start" disabled></el-input>
            </el-form-item>

            <el-button type="info" icon="el-icon-refresh" circle style="margin-left: 70px; margin-right: 70px; "
              @click="exchangeStation" plain disabled></el-button>

            <el-form-item label="到达车站" prop="end">
              <el-input placeholder="请输入车站" style="width: 180px;" v-model="form.end" disabled>
              </el-input>
            </el-form-item>

            <el-form-item style="margin-left: 50px;">
              <el-button :loading="queryLoading" type="primary" size="small" style="margin-left: 60px; "
                @click="setSearch('form')">{{
                  queryLoading ? '查询中...' : '查询' }}</el-button>
              <el-button type="warning" size="small" style="width: 80px; margin-left: 10px;"
                @click="transFormShow('', true, false)" plain>取消改签</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div style="margin-top: 10px;">
          <span style="font-weight: bold;">原有票务信息</span>
          <span style="font-size: medium; color: #93c5fd; margin-left: 30px;"><i class="el-icon-user"></i> 乘车人:</span>
          <span class="text-span">{{ orginTicket.customerName }}</span>
          <span class="label-span"><i class=" el-icon-date"></i> 日期：</span>
          <span class="text-span">{{ orginTicket.date }}</span>
          <span class="label-span"><i class=" el-icon-position"></i> 车次：</span>
          <span class="text-span">{{ orginTicket.trainNumber }}</span>
          <span class="label-span"><i class=" el-icon-map-location"></i> 起始站：</span>
          <span class="text-span">{{ orginTicket.startStation }}</span>
          <span class="label-span"><i class=" el-icon-map-location"></i> 终点站：</span>
          <span class="text-span">{{ orginTicket.arriveStation }}</span>
          <span class="label-span"><i class=" el-icon-s-ticke"></i> 座位类型：</span>
          <el-tag v-if="orginTicket.seatType === 0" type="primary" effect="plain">商务座</el-tag>
          <el-tag v-if="orginTicket.seatType === 1" type="warning" effect="plain">一等座</el-tag>
          <el-tag v-if="orginTicket.seatType === 2" type="info" effect="plain">二等座</el-tag>
          <span class="label-span"><i class=" el-icon-message"></i> 价格：</span>
          <span class="text-span">{{ orginTicket.price }}</span>
        </div>

        <el-table :data="trainData" style="width: auto; height: auto;  margin-top: 10px;" stripe border
          :header-cell-style="{ background: '#f0f9ff', textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form class="expand">
                <div style="width:148px; text-align: center;">
                  <span>历时：{{ props.row.time }}</span>
                </div>
                <div style="width:100px; text-align: center;">
                  <span> ¥{{ props.row.businessPrice }}</span>
                </div>
                <div style="width:100px; text-align: center;">
                  <span> ¥{{ props.row.firstPrice }}</span>
                </div>
                <div style="width:100px; margin-right: 170px; text-align: center;">
                  <span> ¥{{ props.row.secondPrice }}</span>
                </div>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column type="index" width="80" label="序号">
          </el-table-column>
          <el-table-column prop="trainNumber" label="车次">
          </el-table-column>
          <el-table-column prop="startStation" label="出发站">
          </el-table-column>
          <el-table-column prop="startTime" label="出发时间">
          </el-table-column>
          <el-table-column prop="arriveStation" label="到达站">
          </el-table-column>
          <el-table-column prop="arriveTime" label="到达时间">
          </el-table-column>
          <el-table-column prop="business" width="100" label="商务座">
          </el-table-column>
          <el-table-column prop="first" width="100" label="一等座">
          </el-table-column>
          <el-table-column prop="second" width="100" label="二等座">
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-button type="primary" size="small" style="width: 80px;" @click="openDialog(scope.row)">改签</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-collapse-transition>

    <el-dialog title="车票改签" :visible.sync="dialogVisible" width="30%">
      <div v-if="dialog_show === 0">
        <div style="margin-bottom: 20px; display: flex; flex-direction: column; ">
          <div style="margin-bottom: 20px; margin-left: 30px;">
            <span style="font-weight: bold; font-size:medium;"> 日期：</span>
            <span>{{ orginTicket.date }}</span>
          </div>
          <div style="margin-bottom: 20px; margin-left: 30px;">
            <span style="font-weight: bold; font-size:medium;">车次：</span>
            <span>{{ orginTicket.trainNumber }}</span>
          </div>
          <div style="margin-bottom: 20px; margin-left: 30px;">
            <span style="font-weight: bold; font-size:medium;">起始站：</span>
            <span>{{ orginTicket.startStation }}</span>
          </div>
          <div style="margin-bottom: 20px; margin-left: 30px;">
            <span style="font-weight: bold; font-size:medium;"> 终点站：</span>
            <span>{{ orginTicket.arriveStation }}</span>
          </div>
          <div style="margin-bottom: 20px; margin-left: 30px;">
            <span style="font-weight: bold; font-size:medium;"> 选择座位：</span>
            <el-radio-group v-model="updateTicket.seatType">
              <el-radio :label='0' >商务座</el-radio>
              <el-radio :label='1' >一等座</el-radio>
              <el-radio :label='2' >二等座</el-radio>
            </el-radio-group>
          </div>
        </div>
        <span style="margin-left: 130px;">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </span>
      </div>
      <div v-if="dialog_show === 1">
        <div style="display: flex; flex-direction: column; justify-content: center; margin-bottom: 20px;">
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold; ">原有票价为：￥{{ orginTicket.price }}</span>
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold;">现在票价为：￥{{ updateTicket.price }}</span>
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold;">票价差额为：￥{{ price.subPrice }}</span>
          <span style="margin-left: 20px; margin-top: 10px; font-size: xx-small;">注：改签不享受任何优惠政策</span>
          <el-divider></el-divider>
          <span
            style="margin-left: 20px; margin-top: 10px; margin-bottom: 5px; font-weight: bold; font-weight: bold; font-size: large; color: red;">
            实付金额为：{{ price.subPrice }}<span
              style=" font-size: xx-small; ">
              （注：若为负数表示退还金额）</span></span>
        </div>
        <span style="margin-left: 120px;">
          <el-button @click="cancelStep">取 消</el-button>
          <el-button @click="lastStep">上一步</el-button>
          <el-button type="primary" :loading="updateLoading" @click="setUpdateTicket">{{ updateLoading ? '支付中 ...' :
            '确认支付'
          }}</el-button>
        </span>
      </div>

    </el-dialog>
  </el-card>
</template>

<script>

import { toast } from '../../../composables/util'
import { subTc } from '../../../composables/data'
export default {
  name: "ticketChange",
  data() {
    return {
      show_1: true,
      show_2: false,
      userInfo: '',

      listData: [],
      search: '',
      searchLoading: false,
      page: {
        total: 0,
        pageSize: 6,
        currentPage: 1
      },

      // 改签
      orginTicket: {},
      queryLoading: false,
      updateLoading: false,
      ticketData: [],
      dialogVisible: false,
      dialog_show: 0,
      // 查询车票表单
      form: {
        start: '',
        end: '',
        date: '',
      },
      // 查询车票表单校验
      rulesForm: {
        date: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'blur' },
        ],
        start: [
          { required: true, message: '请输入始发站 ', trigger: 'blur' }
        ],
        end: [
          { required: true, message: '请输入目的站 ', trigger: 'blur' }
        ]
      },
      updateTicket: {
        id: '',
        trainId: 0,
        startId: 0,
        arriveId: 0,
        price: 0.0,
        seatType: '',
        discountType: 0,
        personId: 0,
        status: 0,
        date: ''
      },
      price: {
        secondPrice: 0,
        firstPrice: 0,
        businessPrice: 0,
        subPrice: 0
      }
    }
  },
  methods: {
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.GetTicket()
    },

    GetTicket() {
      if (this.search === '') {
        this.request.get("/ticketChange/getAll/" + this.userInfo.id + "/" + this.page.currentPage + "/" + this.page.pageSize).then(
          response => {
            console.log(response);
            if (response.data.code === 1) {
              this.listData = response.data.data.records
              this.page.total = response.data.data.total
              console.log(this.listData);
              this.$message({
                message: '更新页面成功！',
                type: 'success',
                duration: 1000
              });
            }
          },
          error => {
            console.log(error.message)
          }
        ).finally(() => {
          this.loading = false
        }
        )
      } else {
        this.searchTicket()
      }
    },

    // 模糊查询
    setSearchicket() {
      this.searchLoading = true
      setTimeout(() => {
        this.searchTicket()
      }, 1000)
    },
    searchTicket() {
      const customerName = this.search
      this.request.get("/ticketChange/searchTicketByName/" + customerName + "/" + this.page.currentPage + "/" + this.page.pageSize).then(
        response => {
          console.log(response);
          if (response.data.code === 1) {
            this.listData = response.data.data.records
            this.page.total = response.data.data.total
            console.log(this.listData);
            this.$message({
              message: '查询成功！',
              type: 'success',
              duration: 1000
            });
          }else{
            this.$message({
              message: '此乘客没有预定车票！',
              type: 'info',
              duration: 1000
            });
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.searchLoading = false
      }
      )
    },

    // 退票
    setDeleteTiceket(ticketId) {
      this.$confirm('是否确定退票?', '退票', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        setTimeout(() => {
          this.deleteTicket(ticketId)
        }, 1000)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    deleteTicket(ticketId) {
      this.request.post("/ticket/delteTicket/" + ticketId).then(
        response => {
          if (response.data.code === 1) {
            toast("退票成功", this)
            this.GetTicket()
          } else {
            console.log(response);
            toast("退票失败", this, "error")
          }
        }
      ).finally(() => {
        this.deleteLoading = false
      }
      )
    },

    // 改签
    transFormShow(form, show_1, show_2) {
      this.orginTicket = form
      if (form != '') {
        this.form.start = form.startStation
        this.form.end = form.arriveStation
      }
      this.show_1 = show_1
      this.show_2 = show_2
      this.form.date = ''
      this.ticketData = []
    },
    // 查询车票校验
    setSearch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.queryLoading = true
          this.ticketData = []
          const stationName = []
          stationName.push(this.form.start);
          stationName.push(this.form.end);
          setTimeout(() => {
            this.getAllTicket(stationName)
          }, 1000);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 查询车票
    getAllTicket(stationName) {
      console.log(this.form);
      this.request.get('/ticketVo/findTicket/' + stationName + "/" + this.form.date).then(
        response => {
          if (response.data.code === 1) {
            this.ticketData = response.data.data
            console.log(this.ticketData);
            this.total = this.ticketData.length
            this.$message({
              message: '查询成功',
              type: 'success',
              duration: 1000
            });
          } else {
            this.$message({
              message: '查询出错: ' + response.data.msg,
              type: 'error',
              duration: 1000
            })
          }
        },
        error => {
          console.log(error.message)
        }
      )
        .finally(() => {
          this.queryLoading = false
        })
    },
    // 交换车站
    exchangeStation() {
      var mid = this.form.start;
      this.form.start = this.form.end;
      this.form.end = mid;
    },
    openDialog(train) {
      this.dialogVisible = true
      this.updateTicket.id = this.orginTicket.id
      this.updateTicket.trainId = train.trainNumberId
      this.updateTicket.startId = train.startId
      this.updateTicket.arriveId = train.arriveId
      this.updateTicket.discountType = this.orginTicket.discountType
      this.updateTicket.status = 1
      this.updateTicket.personId = this.orginTicket.personId
      this.updateTicket.date = this.form.date
      this.price.businessPrice = train.businessPrice
      this.price.firstPrice = train.firstPrice
      this.price.secondPrice = train.secondPrice
    },
    // 下一步
    nextStep() {
      this.dialog_show++
      if (this.updateTicket.seatType === 2) {
        this.updateTicket.price = this.price.secondPrice
      } else if (this.updateTicket.seatType === 1) {
        this.updateTicket.price = this.price.firstPrice
      } else {
        this.updateTicket.price = this.price.businessPrice
      }
      this.price.subPrice = subTc(this.updateTicket.price, this.orginTicket.price)
    },
    // 上一步
    lastStep() {
      this.dialog_show--
    },
    // 取消
    cancelStep() {
      this.dialogVisible = false,
        this.updateTicket.seatType = ''
      this.lastStep()
    },
    setUpdateTicket() {
      this.updateLoading = true
      console.log(this.updateTicket);
      setTimeout(() => {
        this.putTicket()
      }, 1000)
    },
    putTicket() {
      this.request.put("/ticket/updateTicket", this.updateTicket).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: '改签成功',
              type: 'success',
              duration: 1000
            });
          } else {
            this.$message({
              message: '改签失败',
              type: 'error',
              duration: 1000
            });
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.updateLoading = false
        this.cancelStep()
        this.transFormShow('', true, false)
        this.GetTicket()
      })
    }
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem('login_user'))
    this.GetTicket()
  },
  computed: {
    tableData() {
      return this.listData
    },
    trainData() {
      let listMidData = this.ticketData
      for (let lm of listMidData) {
        if (lm.business > 8) {
          lm.business = '有'
        }
        if (lm.first > 8) {
          lm.first = '有'
        }
        if (lm.second > 8) {
          lm.second = '有'
        }
      }
      return listMidData
    }
  }
}

</script>

<style scoped>
.el-card {
  margin-top: 10px;
  width: 100%;
  min-height: 83vh;
}

.label-span {
  margin-left: 50px;
  font-size: medium;
  color: #93c5fd;
}

.text-span {
  font-weight: bold;
}

.expand {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: nowrap;
  align-content: center;
  font-weight: bold;
  color: #334155;
}

::v-deep .el-table__empty-block {
  /* justify-content: center; */
  min-height: 345px;
}</style>